'use client'

import React, { useState, useEffect, useCallback } from 'react'
import styles from './typewriter.module.css'

interface TypewriterProps {
  text: string
  speed?: number
  delay?: number
  loop?: boolean
  className?: string
  onComplete?: () => void
}

const Typewriter: React.FC<TypewriterProps> = ({
  text,
  speed = 100,
  delay = 1500,
  loop = false,
  className = '',
  onComplete,
}) => {
  const [displayText, setDisplayText] = useState('')
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isDeleting, setIsDeleting] = useState(false)
  const [isComplete, setIsComplete] = useState(false)

  const typeText = useCallback(() => {
    // 如果已经完成并且不循环，则不执行任何操作
    if (isComplete && !loop) return

    // 删除模式
    if (isDeleting) {
      setDisplayText(prev => prev.substring(0, prev.length - 1))

      // 如果已经删除完毕，切换到打字模式
      if (displayText.length === 0) {
        setIsDeleting(false)
        setCurrentIndex(0)
      }
    }
    // 打字模式
    else {
      // 设置当前要显示的文本
      setDisplayText(text.substring(0, currentIndex + 1))
      setCurrentIndex(prev => prev + 1)

      // 如果已经打完全部文本
      if (currentIndex >= text.length - 1) {
        if (loop) {
          // 如果需要循环，设置延迟后开始删除
          setTimeout(() => {
            setIsDeleting(true)
          }, delay)
        } else {
          // 如果不需要循环，标记为完成
          setIsComplete(true)
          onComplete?.()
        }
      }
    }
  }, [currentIndex, delay, displayText.length, isComplete, isDeleting, loop, onComplete, text])

  useEffect(() => {
    if (isComplete && !loop) return

    const timer = setTimeout(typeText, isDeleting ? speed / 2 : speed)

    return () => clearTimeout(timer)
  }, [displayText, isDeleting, isComplete, loop, speed, typeText])

  return (
    <span className={`${styles.typewriter} ${className}`}>
      {displayText}
      {/* <span className={styles.cursor}>|</span> */}
    </span>
  )
}

export default Typewriter
